<template>
    <div class="resume-container">
        <el-card class="box-card" shadow="always" style="margin-bottom: 20px;">
            <!-- 顶部标签与收起按钮 -->
            <div style="display: flex; justify-content: space-between; align-items: center;width:100%">
                <div style="width:100%">
                    <el-button class="yellow-btn" @click="activeTab = 'parser'" size="normal">
                        简历解析
                    </el-button>
                    <el-button class="yellow-btn" @click="activeTab = 'portrait'" size="normal">
                        简历画像
                    </el-button>

                </div>
                <!-- <el-button type="text" icon="el-icon-arrow-up" @click="showTopPanel = !showTopPanel">
                    {{ showTopPanel ? '收起' : '展开' }}
                </el-button> -->
                <el-button type="text" icon="el-icon-arrow-up" @click="showTopPanel = !showTopPanel"
                    class="custom-toggle-button">
                    {{ showTopPanel ? '收起' : '展开' }}
                </el-button>
            </div>

            <!-- 折叠上传区域 -->
            <el-collapse-transition>
                <div v-show="showTopPanel" class="upload-wrapper" style="margin-top: 10px;">
                    <el-divider style="margin-top: 10px; margin-bottom: 10px;width:100%" />
                    <!-- 拖拽上传样式，仅用于展示 -->
                    <!-- 自定义上传器 -->
                    <!-- <div style="margin-top: 10px;">
                        <input type="file" @change="handleFileChange" accept=".doc,.docx,.pdf" />
                        <el-button size="small" type="primary" @click="uploadResume"
                            :disabled="!selectedFile">解析简历</el-button>
                        <div class="el-upload__tip">仅支持 PDF 或 DOC/DOCX 格式文件</div>
                    </div> -->
                    <div style="margin-top: 10px;display:flex;flex-direction: row;align-items: center;">
                        <!-- 隐藏原始 input -->
                        <input ref="fileInput" type="file" style="display: none" @change="handleFileChange"
                            accept=".doc,.docx,.pdf" />

                        <!-- 自定义按钮触发文件选择 -->
                        <el-button size="small" type="primary" @click="triggerFileInput" class="yellow-btn">
                            {{ selectedFile ? '重新上传' : '选择简历文件' }}
                        </el-button>

                        <div v-if="selectedFile"
                            style="color: #666; max-width: 60%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;padding-left: 20px;">
                            {{ selectedFile.name }}
                        </div>

                        <!-- 上传按钮 -->
                        <el-button class="yellow-btn" size="small" type="success" @click="uploadResume"
                            :disabled="!selectedFile" style="margin-left: 10px">
                            解析简历
                        </el-button>


                    </div>
                    <div class="el-upload__tip">仅支持 PDF 或 DOC/DOCX 格式文件</div>

                    <!-- 状态信息 -->
                    <div v-if="loading">解析中，请稍候...</div>
                    <div v-if="error" style="color:red">{{ error }}</div>
                    <!-- <div v-if="resumeData.status.code !== 0">
                        <p>解析结果：</p>
                        <pre class="pre-line">{{ resumeData }}</pre>
                    </div> -->
                </div>
            </el-collapse-transition>
        </el-card>
        <!-- 基本信息卡片 -->
        <el-card class="box-card" shadow="always" v-if="resumeData.status.code !== 0">
            <div class="user-info">
                <div class="avatar-box">
                    <img :src="resumeData.result.avatar_data" alt="证件照"
                        style="width: 100px; height: auto; border-radius: 4px;">
                </div>
                <div class="info-box">
                    <div style="display: flex;flex-direction: row;align-items: center;gap: 10px;">
                        <h2><strong>{{ resumeData.result.name }}</strong></h2>
                        <!-- <p>{{ resumeData.position }}</p> -->
                    </div>
                    <div
                        style="margin-top: 10px; display: flex; flex-direction: row; gap: 5px; flex-wrap: wrap;line-height: 1.5;">
                        <template v-for="(highlight, i) in uniqueHighlights">
                            <el-tag :key="i" v-if="highlight.title" type="primary" size="normal" effect="dark" round
                                style="font-size: 15px; height: 22px; line-height: 22px; padding: 0 10px; display: inline-flex; align-items: center; justify-content: center;">
                                {{ highlight.title }}
                            </el-tag>
                        </template>

                        <el-tag type="primary" size="success" effect="dark" color="#17A2B8" round
                            style="font-size: 14px; height: 22px; line-height: 22px; display: inline-flex; align-items: center; justify-content: center;"
                            v-if="resumePaint.profiler_result.predicted_salary">
                            {{ resumePaint.profiler_result.predicted_salary }}
                        </el-tag>
                    </div>
                </div>
            </div>
            <el-divider></el-divider>
            <el-row :gutter="20" justify="center" style="line-height: 1.5;">
                <el-col :span="6"><i class="el-icon-user"></i> {{ resumeData.result.gender }}</el-col>
                <el-col :span="6"><i class="el-icon-date"></i> {{ resumeData.result.age }}岁</el-col>
                <el-col :span="6"><i class="el-icon-location"></i> {{ resumeData.result.city }}</el-col>
                <el-col :span="6"><i class="el-icon-suitcase"></i> {{ resumeData.result.work_year }}年经验</el-col>
                <el-col :span="6"><i class="el-icon-school"></i> {{ resumeData.result.college }}</el-col>
                <el-col :span="6"><i class="el-icon-tickets"></i> {{ resumeData.result.degree }}</el-col>
                <el-col :span="5"><i class="el-icon-phone"></i> {{ resumeData.result.phone }}</el-col>
                <el-col :span="7"><i class="el-icon-message"></i> {{ resumeData.result.email }}</el-col>
            </el-row>
            <div style="width:100%">
                <resumeAnalyze v-if="activeTab === 'parser' && resumeData.status.code !== 0" :resumeData="resumeData" />
                <resumePaint v-if="activeTab === 'portrait' && resumePaint.status.code !== 0"
                    :resumePaint="resumePaint" />
            </div>


        </el-card>
        <div style="width:100%;">
            <previewCard v-if="resumeData.status.code == 0" :activeTab="activeTab" />
        </div>

    </div>
</template>

<script>
import resumeSDK from '@/store/modules/resumeSDK';
import resumePaint from './resumePaint.vue';
import resumeAnalyze from './resumeAnalyze.vue'
import previewCard from './previewCard.vue'
import axios from 'axios';

export default {
    components: {
        resumeSDK,
        resumePaint,
        resumeAnalyze,
        previewCard
    },
    data() {
        return {
            showTopPanel: true,
            activeTab: 'parser',
            selectedFile: null,
            base64FileContent: '',
            error: '',
            loading: false,
            formattedResult: '', // 用于展示的字符串（可选）
            resumeData: {
                status: {
                    message: '',
                    code: 0
                },
                result: {
                    name: '',
                    gender: '',
                    age: '',
                    marital_status: '',
                    polit_status: '',
                    major: '',
                    surname: '',
                    height: '',
                    weight: '',
                    birthday: '',
                    city_norm: '',
                    college: '',
                    college_type: '',
                    college_rank: '',
                    has_oversea_edu: '',
                    has_oversea_exp: '',
                    city: '',
                    grad_time: '',
                    degree: '',
                    race: '',
                    nationality: '',
                    english_level: '',
                    computer_level: '',
                    work_position: '',
                    work_company: '',
                    work_industry: '',
                    work_start_time: '',
                    work_year_norm: '',
                    work_year: '',
                    work_job_nature: '',
                    work_start_time_inf: '',
                    phone: '',
                    email: '',
                    postal_code: '',
                    qq: '',
                    weixin: '',
                    expect_salary: '',
                    expect_salary_min: '',
                    expect_salary_max: '',
                    expect_job: '',
                    expect_industry: '',
                    living_address: '',
                    living_address_norm: '',
                    hukou_address_norm: '',
                    hukou_address: '',
                    hometown_address_norm: '',
                    hometown_address: '',
                    resume_type: '',
                    resume_source: '',
                    resume_integrity: '',
                    resume_parse_time: '',
                    resume_name: '',
                    avatar_data: '',
                    education_objs: [
                        {
                            edu_college: '',
                            edu_major: '',
                            start_date: '',
                            end_date: '',
                            edu_degree: '',
                            edu_degree_norm: '',
                            edu_college_rank: '',
                            edu_college_type: ''
                        }
                    ],
                    job_exp_objs: [
                        {
                            job_position: '',
                            end_date: '',
                            job_content: '',
                            job_cpy: '',
                            job_industry: '',
                            job_cpy_size: '',
                            job_duration: '',
                            start_date: '',
                            job_dept: ''
                        }
                    ],
                    proj_exp_objs: [
                        {
                            proj_position: '',
                            proj_resp: '',
                            proj_name: '',
                            start_date: '',
                            end_date: ''
                        }
                    ],
                    training_objs: [
                        {
                            train_org: '',
                            train_cont: ''
                        }
                    ],
                    cert_objs: [
                        {
                            langcert_lang: '',
                            langcert_name: ''
                        }
                    ],
                    all_cert_objs: [
                        {
                            cert_type: '',
                            cert_name: ''
                        }
                    ],
                    lang_objs: [
                        {
                            language_name: ''
                        }
                    ],
                    skills_objs: [
                        {
                            skills_name: '',
                            skills_level: ''
                        }
                    ],
                    cont_basic_info: '',
                    cont_expect_job: '',
                    cont_education: '',
                    cont_job_exp: '',
                    cont_proj_exp: '',
                    cont_job_skill: '',
                    raw_text: ''
                },
                tags: {
                    industries: [
                        {
                            tag_weight: '',
                            tag_name: ''
                        }
                    ],
                    pos_types: [
                        {
                            tag_weight: '',
                            tag_name: ''
                        }
                    ],
                    pos_tags: [
                        {
                            tag_weight: '',
                            tag_name: ''
                        }
                    ],
                    skills_tags: [
                        {
                            tag_weight: '',
                            tag_name: ''
                        }
                    ]
                },
                eval: {
                    salary: ''
                }
            },
            resumePaint: {
                status: {
                    message: 'success',
                    code: 0
                },
                result: {},
                profiler_result: {
                    basic: [
                        { tag: "女", type: "gender" },
                        { tag: "30-35岁", type: "age" },
                        { tag: "10年以上经验", type: "experience" }
                    ],
                    education: [
                        { tag: "学士学历", type: "degree" },
                        { tag: "旅游管理专业", type: "major" },
                        { tag: "辽宁大学", type: "college" },
                        { tag: "211院校", type: "college_level" }
                    ],
                    job_exp: [
                        { tag: "旅游平台", type: "position" },
                        { tag: "网站编辑和美工", type: "position" },
                        { tag: "设计-互联网设计-美工/电商设计师", type: "position_type" },
                        { tag: "运营-电商运营-国内电商运营", type: "position_type" },
                        { tag: "酒店/旅游-旅游-旅游产品销售", type: "position_type" },
                        { tag: "服务业-美容/保健", type: "industry" }
                    ],
                    skills: {
                        job_skills: [
                            { tag: "宝贝描述", type: "互联网设计", weight: 83 },
                            { tag: "处理图片", type: "业务运营", weight: 78 },
                            { tag: "产品图片", type: "互联网设计", weight: 78 }
                        ],
                        soft_skills: [
                            { tag: "文字表达能力" },
                            { tag: "团队合作" }
                        ],
                        hobbies: [
                            { tag: "旅游" },
                            { tag: "音乐" }
                        ],
                        languages: [
                            { tag: "英语" },
                            { tag: "日语" }
                        ],
                        certificates: [
                            { tag: "导游资格证" },
                            { tag: "大学英语4级" },
                            { tag: "大学英语6级" }
                        ],
                        awards: []
                    },
                    stability: {
                        average_job_time: 43.0,
                        average_job_type_time: 43.0,
                        average_industry_time: 43.0,
                        long_job_time_num: 1,
                        short_job_time_num: 1,
                        job_stability: "稳定"
                    },
                    capacity: {
                        education: 30,
                        honor: 10,
                        language: 70,
                        management: 10,
                        job_exp: 30,
                        social_exp: 10
                    },
                    predicted_pos_types: [
                        { c1: "设计", c2: "互联网设计", c3: "美工/电商设计师", weight: 17 },
                        { c1: "运营", c2: "电商运营", c3: "国内电商运营", weight: 16 },
                        { c1: "酒店/旅游", c2: "旅游", c3: "旅游产品销售", weight: 8 }
                    ],
                    predicted_industries_c1: [
                        { c1: "服务业", weight: 53 },
                        { c1: "贸易/消费/制造/营运", weight: 26 },
                        { c1: "房地产/建筑", weight: 20 },
                        { c1: "专业服务/教育/培训", weight: 0 },
                        { c1: "能源/环保/化工", weight: 0 },
                        { c1: "政府/非营利组织/其他", weight: 0 },
                        { c1: "广告/媒体", weight: 0 },
                        { c1: "制药/医疗", weight: 0 },
                        { c1: "会计/金融/银行/保险", weight: 0 },
                        { c1: "物流/运输", weight: 0 },
                        { c1: "计算机/互联网/通信/电子", weight: 0 }
                    ],
                    predicted_industries_c2: [
                        { c1: "服务业", c2: "美容/保健", weight: 9 },
                        { c1: "贸易/消费/制造/营运", c2: "批发/零售", weight: 8 },
                        { c1: "服务业", c2: "娱乐/休闲/体育", weight: 7 },
                        { c1: "房地产/建筑", c2: "家居/室内设计/装潢", weight: 6 }
                    ],
                    predicted_salary: "5-10K",
                    highlights: [
                        {
                            title: "工作稳定",
                            content: "【工作稳定】：平均每段工作经历持续【43】个月，且存在【1】段工作经历2年以上",
                            type: "job_exp"
                        },
                        {
                            title: "",
                            content: "在【国内电商运营】职能领域和【美容/保健】行业里有【较丰富】工作经历",
                            type: "job_exp"
                        },
                        {
                            title: "211院校",
                            content: "【较不错】的教育背景：学士学历，毕业于【211院校】",
                            type: "education"
                        }
                    ],
                    risks: [
                        {
                            title: "工作不稳定",
                            content: "【工作不稳定】：平均每段工作经历仅持续【10】个月，且存在【1】段工作经历1年以下",
                            type: "job_exp"
                        },
                        {
                            title: "空档期",
                            content: "【空档期】：候选人在 2014.06~2015.07 期间共存在【13个月】的职业空档期",
                            type: "job_exp"
                        }
                    ]
                }
            },

        }
    },
    computed: {
        // 计算属性：返回去重后的 highlights 列表
        uniqueHighlights() {
            const titles = new Set(); // 使用 Set 存储已出现的 title
            return this.resumePaint.profiler_result.highlights.filter(highlight => {
                if (highlight.title && !titles.has(highlight.title)) {
                    titles.add(highlight.title);
                    return true;
                }
                return false;
            });
        }
    },
    methods: {
        handleFileChange(event) {
            const file = event.target.files[0];

            if (!file) {
                this.selectedFile = null;
                return;
            }

            const allowedTypes = [
                "application/msword",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                "application/pdf",
            ];

            if (!allowedTypes.includes(file.type)) {
                this.error = "请上传.doc、.docx或.pdf格式的简历文件";
                this.selectedFile = null;
                return;
            }

            this.selectedFile = file;

            const reader = new FileReader();
            reader.onload = () => {
                const base64String = reader.result.split(",")[1];
                this.base64FileContent = base64String;
            };
            reader.onerror = () => {
                this.error = "读取文件失败";
                this.selectedFile = null;
            };
            reader.readAsDataURL(file);
        },

        triggerFileInput() {
            this.$refs.fileInput.click();
        },

        async uploadResume() {
            if (!this.selectedFile || !this.base64FileContent) {
                this.error = "请先选择简历文件";
                return;
            }

            this.loading = true;
            this.error = "";

            const url_parser = "https://resumesdk.market.alicloudapi.com/ResumeParser";
            const url_profiler = "https://aliprofile.market.alicloudapi.com/ResumeProfiler";
            // const appcode = "55eda8e822e2421499fcc94005405d82";
            const appcode = "c69a92a5c3bd446bab58229251f622de";

            const data = {
                file_name: this.selectedFile.name,
                file_cont: this.base64FileContent,
                need_avatar: 1,
            };

            try {
                console.log("准备发送请求:", data, "headers:", {
                    Authorization: "APPCODE " + appcode,
                    "Content-Type": "application/json; charset=UTF-8"
                });
                const response_parser = await axios.post(url_parser, data, {
                    headers: {
                        Authorization: "APPCODE " + appcode,
                        "Content-Type": "application/json; charset=UTF-8",
                    },
                });
                const response_profiler = await axios.post(url_profiler, data, {
                    headers: {
                        Authorization: "APPCODE " + appcode,
                        "Content-Type": "application/json; charset=UTF-8",
                    },
                });

                if (response_parser.status === 200) {
                    this.resumeData = response_parser.data;
                    // resumeAnalyze.resumeData = response_parser.data;
                    this.$message.success("简历解析成功！");
                } else {
                    this.error = `请求失败，状态码：${response_parser.status}`;
                }

                if (response_profiler.status === 200) {
                    this.resumePaint = response_profiler.data;
                    // resumePaint.resumePaint = response_profiler.data;
                    this.selectedFile = null;
                    this.$message.success("简历画像成功！");
                } else {
                    this.error = `请求失败，状态码：${response_profiler.status}`;
                }


            } catch (err) {
                if (err.response && err.response.data) {
                    this.error = "请求错误：" + JSON.stringify(err.response.data);
                } else {
                    this.error = "请求错误：" + err.message;
                }
            } finally {
                this.loading = false;
            }
        },
        getCollegeTypeName(typeCode) {
            const typeMap = {
                '0': '普通院校',
                '1': '985',
                '2': '211',
                '3': '港澳台院校',
                '4': '海外院校',
                '5': '中学',
                '6': '职业教育',
                '7': '培训机构'
            };
            return typeMap[String(typeCode)] || '未知类型';
        },
        getResumeTypeName(typeCode) {
            const typeMap = {
                '0': '中文（简体）',
                '1': '英文',
                '2': '中英（前中后英）',
                '3': '英中（前英后中）',
                '4': '空',
                '10': '中文（繁体）'
            };
            return typeMap[String(typeCode)] || '未知类型';
        },

    }
}

</script>

<style scoped>
.box-card {
    background-color: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 12px 0 rgba(200, 180, 120, 0.08);
    border: 1px solid #f0e6d2;
    width: 100%;
}

.yellow-btn {
    background-color: #f9f3cf;
    /* 按钮默认背景色：黄色 */
    border-color: #fadf35;
    color: #694600;
    /* 文字颜色 */
}

.yellow-btn:hover,
.yellow-btn:focus {
    background-color: #f7d25c;
    /* hover 或 focus 时变浅黄色 */
    border-color: #eebb14;
    color: #fff;
}

.yellow-btn:active {
    background-color: #f5cc5c;
    /* 点击时略深 */
    border-color: #f4c134;
    color: #fff;
}

.yellow-btn.is-disabled {
    background-color: #f5f5f5;
    border-color: #f0f0f0;
    color: #aaa;
}

/* 止 disabled 按钮 hover 后变色 */
.yellow-btn.is-disabled,
.yellow-btn.is-disabled:hover {
    background-color: #f5f5f5 !important;
    border-color: #d9d9d9 !important;
    color: #bfbfbf !important;
    cursor: not-allowed;
}

/* 按钮基础样式 */
.custom-toggle-button {
    color: #8B4513 !important;
    /* 棕色文字 */
    font-size: 16px;
    /* 增大字体 */
    padding: 0;
    line-height: 1;
}

/* 按钮悬停效果 */
.custom-toggle-button:hover {
    color: #A0522D !important;
    text-decoration: underline;
}

/* 图标样式 */
.custom-toggle-button .el-icon-arrow-up {
    margin-right: 4px;
}

.resume-container {
    padding: 20px;
    max-width: 90%;
    margin: auto;
    font-family: "Times New Roman", serif;
}

.user-info {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 20px;
}

.avatar-box {
    margin-right: 20px;
    height: 100%;
    aspect-ratio: 5 / 7;
    background-color: aliceblue;
}

.info-box h2 {
    margin: 0;
    font-weight: bold;
    display: flex;
    flex-direction: column;
}

.tags {
    margin-top: 10px;
    display: flex;
    flex-direction: row;
    gap: 5px;
}

.project-block {
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.responsibility-list {
    padding-left: 1.5em;
    /* 左边缩进整个列表 */
    margin: 4px 0 8px 0;
    line-height: 1.5;
}

.responsibility-list li {
    line-height: 1.2;
    text-indent: 0;
    /* 默认不要缩进第一行，统一由 padding 控制 */
    line-height: 1.5;
}

.dot {
    display: inline-block;
    width: 5px;
    height: 5px;
    background-color: rgb(255, 180, 54);
    border-radius: 50%;
    margin-right: 6px;
    position: relative;
    top: -3px;
}

.upload-demo {
    width: 100%;
    margin-top: 10px;
}
</style>
